package com.newshub.ai.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 数据查询执行器服务
 */
@Slf4j
@Service
public class DataQueryExecutor {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    /**
     * 执行查询并返回结果
     */
    public List<Map<String, Object>> executeQuery(String sql) {
        try {
            log.info("执行 SQL 查询: {}", sql);
            long startTime = System.currentTimeMillis();
            
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
            
            long endTime = System.currentTimeMillis();
            log.info("查询执行完成，耗时: {}ms，返回 {} 条记录", endTime - startTime, result.size());
            
            return result;
        } catch (Exception e) {
            log.error("查询执行失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询执行失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行查询并返回单个值
     */
    public Object executeQueryForObject(String sql, Class<?> requiredType) {
        try {
            log.info("执行单值查询: {}", sql);
            return jdbcTemplate.queryForObject(sql, requiredType);
        } catch (Exception e) {
            log.error("单值查询执行失败: {}", e.getMessage(), e);
            throw new RuntimeException("单值查询执行失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查数据库连接
     */
    public boolean checkConnection() {
        try {
            jdbcTemplate.queryForObject("SELECT 1", Integer.class);
            return true;
        } catch (Exception e) {
            log.error("数据库连接检查失败: {}", e.getMessage());
            return false;
        }
    }
    
    /**
     * 获取数据库表信息
     */
    public List<Map<String, Object>> getTableInfo() {
        try {
            String sql = "SHOW TABLES";
            return jdbcTemplate.queryForList(sql);
        } catch (Exception e) {
            log.error("获取表信息失败: {}", e.getMessage());
            throw new RuntimeException("获取表信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取表结构信息
     */
    public List<Map<String, Object>> getTableStructure(String tableName) {
        try {
            String sql = "DESCRIBE " + tableName;
            return jdbcTemplate.queryForList(sql);
        } catch (Exception e) {
            log.error("获取表结构失败: {}", e.getMessage());
            throw new RuntimeException("获取表结构失败: " + e.getMessage());
        }
    }
}

